package net.gdface.httpclient;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;

import net.gdface.utils.Assert;

import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUtility {
	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtility.class);

	protected static final int DEFAULT_MAX_CONNECTIONS=64;
	protected static final int DEFAULT_MAX_CONNECTIONS_PER_HOST=8;
	/**
	 * 连接超时参数(毫秒)
	 * -1为使用系统默认值
	 */
	public static final int TIME_OUT_MILLS = 40*1000;
	/**
	 * 默认的请求配置对象,所有的请求对象都在这个基础上copy生成 设置cookie策略为BROWSER_COMPATIBILITY
	 */
	public static final RequestConfig BASE_REQUEST_CONFIG = RequestConfig.custom()
			.setCookieSpec(CookieSpecs.DEFAULT)
			.setMaxRedirects(20)
			//设置连接池请求超时
			//.setConnectionRequestTimeout(TIME_OUT_MILLS)
			.setSocketTimeout(HttpClientUtility.TIME_OUT_MILLS)
			.setConnectTimeout(HttpClientUtility.TIME_OUT_MILLS).build();

	public static HttpGet createHttpGET(URI uri, RequestConfig config, NameValuePair... headers) {
		Assert.notNull(uri, "url");
		HttpGet get = new HttpGet(uri);
		get.setConfig(null == config ? BASE_REQUEST_CONFIG : config);
		get.setHeader(HTTPConstants.HEADER_USER_AGENT,
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65 Safari/537.36");
		get.setHeader(HTTPConstants.HEADER_ACCEPT,
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		get.setHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, "gzip,deflate,sdch");
		get.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
		get.setHeader(HTTPConstants.HEADER_CACHE_CONTROL, "max-age=0");
		// get.setHeader(HTTPConstants.HEADER_CACHE_CONTROL, HTTPConstants.HEADER_CACHE_CONTROL_NOCACHE);
		// 解决句柄用完的问题 open_socket_in(): socket() call failed: Too many open files
		// 如果设置为keep-alive，则在大量线程并发状态下会导致文件句柄用尽的问题
		// get.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.HEADER_CONNECTION_CLOSE);
		// 还是尝试用keep-alive,因为有可能设置为close时，会被服务器识别为非浏览器而拒绝，
		// 为避免出现上述文件句柄用尽的问题，在httpclient初始化时，设置NoConnectionReuseStrategy策略，请求结束关闭连接
		get.setHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.HEADER_CONNECTION_KEEPALIVE);
		get.setHeader(HTTPConstants.HEADER_HOST, uri.getHost());
		for (NameValuePair h : headers) {
			if (h.getValue() != null)
				get.setHeader(h.getName(), h.getValue());
		}
		return get;
	}

	public static void main(String args[]) throws MalformedURLException, URISyntaxException {}


}
